package com.cn.delan.web.mvc.admin.action;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.cn.delan.web.mvc.admin.AdminConst;
import com.cn.delan.web.mvc.core.action.AbstractAction;
/**
 * 文件下载
 * @author BingGo
 *
 */
public class DownloadAction extends AbstractAction {

	@Override
	public ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String path = this.getParameter(AdminConst.REQUEST_PARA_PATH);
		File file = new File(path);
		if(file.isFile()){
			//设置为下载application/x-download 
			response.setContentType("application/x-download");
			String filedisplay = file.getName(); 
			filedisplay = URLEncoder.encode(filedisplay,"UTF-8"); 
			//设置下载时保存的文件名
			response.addHeader("Content-Disposition","attachment;filename=" + filedisplay); 
			ServletOutputStream writer = response.getOutputStream();
			int length = -1;
			byte []b = new byte[2000];
			FileInputStream reader = new FileInputStream(file);
			while((length=reader.read(b))!=-1){
				writer.write(b, 0, length);
			}
			writer.flush();
			reader.close();
		}
		return null;
	}

}
